package com.issac.vhr.service;

import com.issac.vhr.entity.Department;
import com.issac.vhr.mapper.DepartmentMapper;
import com.issac.vhr.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EmployeeMapper employeeMapper;

    public List<Department> getAllDepartmentByParentId(Integer pid) {
        return departmentMapper.getAllDepartmentByParentId(pid);
    }

    /*
     * 1.添加
     * 2.查询parentId的DepPath + 自己的id组成自己的depPath
     * 3.查询父部门isParent t/f t不变 f改t
     *
     * department 前端传入来的
     * parentDepartment 根据前端传入的department.parentId查出来的
     * */
    @Transactional
    public Boolean addDepartment(Department department) {
        //department需要主键回填 => 修改逆向工程sql
        if (departmentMapper.insertSelective(department) == 1) {
            Department parentDepartment = departmentMapper.getParentDepartment(department.getParentId());
            department.setDepPath(parentDepartment.getDepPath() + "." + department.getId());
            departmentMapper.updateByPrimaryKeySelective(department);
            if (!parentDepartment.getIsParent()) {
                parentDepartment.setIsParent(true);
                departmentMapper.updateByPrimaryKeySelective(parentDepartment);
            }
            return true;
        }
        return false;
    }

    /*
     *
     * 1.查询当前记录是否有子部门,有子部门删除失败
     * 2.查询当前记录是否有员工,有员工删除失败
     * 3.查询当前记录父部门是否有子部门,无则修改isParent为false
     *
     * */
    @Transactional
    public boolean deleteDepartment(Integer id) {
        Department department = departmentMapper.selectByPrimaryKey(id);
        if (!department.getIsParent()) {
            if (employeeMapper.getEmployeeBydepartmentId(id) == 0) {
                Department parentDepartment = departmentMapper.selectByPrimaryKey(department.getParentId());
                if (departmentMapper.isOnlyOneChildrenDepartment(department.getParentId())==1){
                    parentDepartment.setIsParent(false);
                    departmentMapper.updateByPrimaryKeySelective(parentDepartment);
                }
                departmentMapper.deleteByPrimaryKey(id);
                return true;
            }
        }
        return false;
    }

    public List<Department> getAllDepartment(){
        return departmentMapper.getAllDepartment();
    }
}
